<?php
namespace Personnelsystem\Controller;
use Think\Controller;
use Think\Model;
use Think\Page;
require('lib/PHPExcel.php');
require('lib/PHPExcel/IOFactory.php');

define('LG','cn');  //定死语言是汉语

ob_end_clean();
header("content-type:text/html;charset=utf-8");
class KaoqinController extends LoginTrueController {

    public function Lists(){
        $this->LoginTrue();
        $kaoqin=M("kaoqin");
		$variables=M("variables");
		$regione=M("regione");
		$department=M("department");
		$staff=M("staff");
		$lib=new LibController();

		//下面对自定义变量的处理
		$rs_kabouts = $variables->where("vId=7")->find();  //处理会议类型
		$rs_kaboutval=unserialize(stripslashes($rs_kabouts["vVariablesVal"]));
        $rs_kabout = $rs_kaboutval[LG];
		
        $stName=$_POST["stName"];  //姓名查询
		$stSex=$_POST["stSex"];  //性别查询
		$stIDCard=$_POST["stIDCard"];  //身份证查询
		$startdate=$_POST["startdate"];  //开始时间查询
		$enddate=$_POST["enddate"];  //结束时间查询
		$kabout=$_POST["kabout"];  //会议类型查询
		$xiaozu=$_POST["xiaozu"];  //小组查询

		$search_type=$_POST["search_type"];  //统计类型
		$search_year=$_POST["search_year"];  //统计年
		$search_month=$_POST["search_month"];  //统计月
		$search_week=$_POST["search_week"];  //统计周
		if(empty($search_type)){
			$search_type="year";
			$search_year=date("Y");
			$search_month=date("m");
		}

		$where=" kId > 0 ";

		if($search_type=="year"){//按年月周统计查询
			$endyear=$search_year+1;
			$startSearch=strtotime($search_year.'-01-01');
			$endSearch=strtotime($endyear.'-01-01');
			$where.=" and ktime>{$startSearch}";
			$where.=" and ktime<{$endSearch}";
		}elseif($search_type=="month"){
			$startSearch=strtotime($search_year.'-'.$search_month.'-01');
			$endSearch=strtotime($search_year.'-'.$search_month.'-01'." +1 month");
			$where.=" and ktime>{$startSearch}";
			$where.=" and ktime<{$endSearch}";
		}elseif($search_type=="week"){
			$searchdate=explode('|',$search_week);
			$startSearch=strtotime($searchdate[0]);
			$endSearch=strtotime($searchdate[1]." +1 day");
			$where.=" and ktime>{$startSearch}";
			$where.=" and ktime<{$endSearch}";
		}

		if(empty($_POST["regione1"])){
			$regione1=$regione->where("pId='650000000000'")->select();
		}
		$regioneid=$_POST["regione1"];  //地区查询
		if(!empty($_POST["regione2"])){
			$regioneid=$_POST["regione2"];
		}
		if(!empty($_POST["regione3"])){
			$regioneid=$_POST["regione3"];
		}
		if(!empty($_POST["regione4"])){
			$regioneid=$_POST["regione4"];
		}
		if(!empty($xiaozu)){
			$xiaozuInfo=$department->field('pId')->where("dId=$xiaozu")->find();
			$regioneid=$xiaozuInfo['pId'];
		}
		$regione_list=$regione->select();
		if(!empty($regioneid)){     //如果地区查询，且没选择小组
			if(empty($xiaozu)){
				$lib->relist=$regioneid;
				$lib->createtree($regione_list,$regioneid);
				$where.=" and regioneNum in($lib->relist)";
				$userwhere=" regioneNum in($lib->relist)";
			}

			$lib->getFatherRegione($regione_list,$regioneid);
			//print_r(session('regione1'));
			$flagFn=$fn=count($lib->father_Regione);
			for($fn ;$fn>0;$fn--){
				if($fn==1){
						$regione1=session('regione1');
						//$regione1[]=$lib->father_Regione[$flagFn-1];
					if($flagFn==1){
						$pId=$lib->father_Regione[$flagFn-1]['id'];
						$regione2=$regione->where("pId=$pId")->select();
					}
				}
				if($fn==2){
					if(!empty(session('regione2'))){
						$regione2=session('regione2');
					}else{
						$regione2=$regione->where("pId='{$_POST['regione1']}'")->select();
					}
					if($flagFn==2){
						$pId=$lib->father_Regione[$flagFn-2]['id'];
						$regione3=$regione->where("pId=$pId")->select();
					}
				}
				if($fn==3){
					if(!empty(session('regione3'))){
						$regione3=session('regione3');
					}else{
						$regione3=$regione->where("pId='{$_POST['regione2']}'")->select();
					}
					if($flagFn==3){
						$pId=$lib->father_Regione[$flagFn-3]['id'];
						$regione4=$regione->where("pId=$pId")->select();
					}
				}
				if($fn==4){
					if(!empty(session('regione4'))){
						$regione4=session('regione4');
					}else{
						$regione4=$regione->where("pId='{$_POST['regione3']}'")->select();
					}
					if($flagFn==4){
						$pId=$lib->father_Regione[$flagFn-4]['id'];
						$xiaozulist=$department->field('dId,dName')->where("pId=$pId")->select();
					}
				}
			}
		}else{
			$regione1=session('regione1');
			$regione2=session('regione2');
			$regione3=session('regione3');
			$regione4=session('regione4');

			if(count($regione4)==1){
				$regioneid=$regione4[0]['id'];
				$xiaozulist=$department->field('dId,dName')->where("pId='{$regioneid}'")->select();
			}

			$lib->relist=session('manageRegione');
			$lib->createtree($regione_list,session('manageRegione'));
			$where.=" and regioneNum in($lib->relist)";
			$userwhere=" regioneNum in($lib->relist)";
		}
		//print_r($regione1);
		if(!empty($stName)){   		//如果查询姓名
			$where.=" and renshi_kaoqin.stName LIKE '%{$stName}%'";
		}
		if(!empty($stIDCard)){		//如果查询身份证
			$where.=" and stIDCard='{$stIDCard}'";
		}
		if(!empty($stSex)){		//如果查询性别
			$where.=" and stSex='{$stSex}'";
		}
		if($kabout!==NULL&&$kabout!=-1){		//如果考勤类型
			$where.=" and kabout='{$kabout}'";
		}else
			$_POST["kabout"]=-1;

		if(!empty($xiaozu)){		//如果查询小组
			$where.=" and xiaozu='{$xiaozu}'";
			$userwhere=" xiaozu='{$xiaozu}'";
		}
		if(!empty($startdate)){
			$startdate=strtotime($startdate);
			$where.=" and ktime>{$startdate}";
		}
		if(!empty($enddate)){
			$enddate=strtotime($enddate);
			$where.=" and ktime<{$enddate}";
		}
		//print_r($userwhere);
		//查询考勤列表

		//处理分页
		if($_POST['page']){
			$pageid=$_POST['page']-1;
			$_GET['p']=$_POST['page'];
		}else
			$pageid=0;
		$count = $kaoqin->where($where)->join('renshi_staff ON renshi_kaoqin.stId = renshi_staff.stId')->count();// 查询满足要求的总记录数 $map表示查询条件
		$Page = new Page($count,10);// 实例化分页类 传入总记录数  没也显示10条
		$Page->rollPage=7;
		$Page -> setConfig('header','<div class="sum">共%TOTAL_ROW%条</div>');
		$Page -> setConfig('first','首页');
		$Page -> setConfig('last','尾页');
		$Page -> setConfig('prev','上一页');
		$Page -> setConfig('next','下一页');
		$show = $Page->show();// 分页显示输出
		$this->assign('page',$show);// 赋值分页输出

		$rs_kaoqinLists=$kaoqin->where($where)->join('renshi_staff ON renshi_kaoqin.stId = renshi_staff.stId')->order('kId desc')->select();

		//统计查询范围内人数
		$userlist=$staff->field("stId")->where($userwhere)->select();
		$userSum=count($userlist);
		//print_r($userSum);
		if($_POST["isDownload"]){
			$this->getExcel($rs_kaoqinLists,$rs_kabout);
		}

		if($search_type=='year'){//按年统计
			$chartdate=$lib->statisticsYear($rs_kaoqinLists,$search_year,$userSum);
		}
		if($search_type=='month'){//按月统计
			$chartdate=$lib->statisticsMonth($rs_kaoqinLists,$search_year,$search_month,$userSum);
		}
		if($search_type=='week'){//按周统计
			$chartdate=$lib->statisticsWeek($rs_kaoqinLists,$search_week,$userSum);
		}
		//print_r($chartdate['userlist']);
		$this->assign("chartdate",json_encode($chartdate));
		$this->assign("userSum",$userSum);


        $this->assign("rs_kaoqinLists",array_slice($rs_kaoqinLists,$pageid*10,10));
		$this->assign("rs_kabout",$rs_kabout);

		$this->assign("stName",$_POST["stName"]);
		$this->assign("stIDCard",$_POST["stIDCard"]);
		$this->assign("stSex",$_POST["stSex"]);
		$this->assign("startdate",$_POST["startdate"]);
		$this->assign("enddate",$_POST["enddate"]);
		$this->assign("xiaozu",$_POST["xiaozu"]);
		$this->assign("kabout",$_POST["kabout"]);

		$this->assign("regione1",$regione1);
		$this->assign("regione2",$regione2);
		$this->assign("regione3",$regione3);
		$this->assign("regione4",$regione4);
		$this->assign("regione1id",$_POST['regione1']);
		$this->assign("regione2id",$_POST['regione2']);
		$this->assign("regione3id",$_POST['regione3']);
		$this->assign("regione4id",$_POST['regione4']);
		$this->assign("xiaozulist",$xiaozulist);

		$this->assign("search_type",$search_type);
		$this->assign("search_year",$search_year);
		$this->assign("search_month",$search_month);
		$this->assign("search_week",$search_week);
        $this->display();
    }
	 public function clockIn(){
		 
        //下面对自定义变量的处理
        $variables=M("variables");
		$staff=M("staff");
		 $department=M("department");
        $rs_kabout = $variables->where("vId=7")->find();  //处理考勤类型
		$kaboutval=unserialize(stripslashes($rs_kabout["vVariablesVal"]));
        $kabout = $kaboutval[LG];
        $this->assign("kabout", $kabout);
		
        $this->LoginTrue();

		 $regione1=session('regione1');
		 $regione2=session('regione2');
		 $regione3=session('regione3');
		 $regione4=session('regione4');

		 if(count($regione4)==1){
			 $regioneid=$regione4[0]['id'];
			 $xiaozulist=$department->field('dId,dName')->where("pId='{$regioneid}'")->select();
			 $userlist=$staff->field('stId,stName,xiaozu')->where("regioneNum='{$regioneid}'")->select();
			 foreach($userlist as $key => $val){//按小组分类
				 $userlistnew[$val['xiaozu']][]=$val;
			 }
			 foreach($xiaozulist as $key => $val){
				$xiaozulistnew[$val['dId']]=$val;
			 }
		 }
		 $this->assign("regione1",$regione1);
		 $this->assign("regione2",$regione2);
		 $this->assign("regione3",$regione3);
		 $this->assign("regione4",$regione4);
		 $this->assign("xiaozulist",$xiaozulistnew);
		 $this->assign("userlist",$userlistnew);
        $this->display();
    }
	//考勤提交
	public function AddKaoqin(){

		$this->LoginTrue();
		$kaoqin=M("kaoqin");
		$users=M("staff");
		if(empty($_POST["stName"])&&$_POST["stIDCard"]&&$_POST["userlist"]){
			echo json_encode(array("error"=>1,"msg"=>"请输入姓名或身份证号"));
			exit;
		}
		if($_POST["kabout"]==""){
			echo json_encode(array("error"=>1,"msg"=>"错误：请选择考勤类型"));
			exit;
		}
		$data["stName"]=$_POST["stName"];
		$data["kType"]=$_POST["kType"];
		$data["kabout"]=$_POST["kabout"];
		$data["addtime"]=time();
		if($data["kType"]){
			$data["ktime"]=strtotime($_POST['date'].' '.$_POST['time']);
			$data["repairTime"]=time();
			$data["reason"]=$_POST["reason"];
		}else{
			$data["ktime"]=time();
		}
		if(!empty($_POST["userlist"])){  //批量打考勤
			foreach($_POST["userlist"] as $key => $val){
				$userinfo=$users->field('stName')->where("stId={$val}")->find();
				$datas[$key]["stId"]=$val;
				$datas[$key]["stName"]=$userinfo['stName'];
				$datas[$key]["kType"]=$_POST['kType'];
				$datas[$key]["kabout"]=$_POST["kabout"];
				$datas[$key]["addtime"]=time();
				if($_POST["kType"]){
					$datas[$key]["ktime"]=strtotime($_POST['date'].' '.$_POST['time']);
					$datas[$key]["repairTime"]=time();
					$datas[$key]["reason"]=$_POST["reason"];
				}else{
					$datas[$key]["ktime"]=time();
				}
			}
			if(!empty($datas)){
				$result=$kaoqin->addAll($datas);
				if($result){
					echo json_encode(array("error"=>0,"msg"=>"添加考勤成功"));
					exit;
				}else{
					echo json_encode(array("error"=>1,"msg"=>"添加考勤失败"));
					exit;
				}
			}else{
				echo json_encode(array("error"=>1,"msg"=>"数据错误"));
				exit;
			}
		}

		if(!empty($data["stName"])){
			$user=$users->where("stName='{$data["stName"]}'")->select();
			if(empty($user)){
				echo json_encode(array("error"=>1,"msg"=>"未找到改用户，请检查姓名是否正确"));
				exit;
			}else{
				$data["stId"]=$user[0]['stId'];
			}
		}
		if(!empty($_POST["stIDCard"])){
			$user=$users->where("stIDCard='{$_POST["stIDCard"]}'")->select();
			if(empty($user)){
				echo json_encode(array("error"=>1,"msg"=>"未找到改用户，请检查身份证是否正确"));
				exit;
			}else{
				$data["stId"]=$user[0]['stId'];
				$data["stName"]=$user[0]['stName'];
			}
		}
		if(!empty($data["stId"])){
			$result=$kaoqin->add($data);
			if($result){
				echo json_encode(array("error"=>0,"msg"=>"添加考勤成功"));
				exit;
			}else{
				echo json_encode(array("error"=>1,"msg"=>"添加考勤失败"));
				exit;
			}
		}else{
			echo json_encode(array("error"=>1,"msg"=>"错误"));
			exit;
		}

	}

    /**
     * //批量增加考勤
     */
    public function batchAddAction(){
        $this->LoginTrue();
        $staffAdd=M("staff");
		$kaoqinAdd=M("kaoqin");

		//下面对自定义变量的处理
		$variables=M("variables");
		$rs_kabout = $variables->where("vId=7")->find();  //处理考勤类型
		$kaboutval=unserialize(stripslashes($rs_kabout["vVariablesVal"]));
		$kabout = $kaboutval[LG];

        $excel=$_FILES["excel"];  //批量考勤excel表
		$objPHPExcelReader = \PHPExcel_IOFactory::load($excel["tmp_name"]);  //加载excel文件
        foreach($objPHPExcelReader->getWorksheetIterator() as $sheet)  //循环读取sheet
		{
			foreach($sheet->getRowIterator() as $row)  //逐行处理
			{
				if($row->getRowIndex()<2)  //确定从哪一行开始读取
				{
					continue;
				}
				foreach($row->getCellIterator() as $cell)  //逐列读取
				{
					
					$val=$cell->getValue();
					if(is_object($val))  $val= $val->__toString();
					if($cell->getColumn()=='A')
					{
						if(!empty($val)){
							$userExcelName = $val; //姓名
						}else{
							break;
						}
					}
					if($cell->getColumn()=='B')
					{
						if(!empty($val)){
							$user=$staffAdd->where(" stIDCard='{$val}'")->select(); //身份证
							if(!empty($user)){
								$data[$row->getRowIndex()]['stId']=$user[0]['stId'];
								$data[$row->getRowIndex()]['stName']=$user[0]['stName'];
								$data[$row->getRowIndex()]['addtime'] = time(); //记录录入系统时间
							}else{
								$this->error($userExcelName."的身份证号：".$val."有误，无法找到该用户");
							}
						}else{
							break;
						}
					}

					if($cell->getColumn()=='C')
					{
						if(!empty($val)){
							$data[$row->getRowIndex()]['ktime'] =strtotime(gmdate("Y-m-d H:i:s", \PHPExcel_Shared_Date::ExcelToPHP($val))); //打卡时间
							$flagtime=$data[$row->getRowIndex()]['ktime'];
						}
					}
					if($cell->getColumn()=='D')
					{
						if(!empty($val)){
							foreach($kabout as $kabout_key => $kabout_val){
								if($val== $kabout_val){
									$data[$row->getRowIndex()]['kabout'] = $kabout_key;
								}
							}
							if($data[$row->getRowIndex()]['kabout']===NULL){
								$this->error('会议类型：'.$val.'不存在');
							}
						}
					}	
					if($cell->getColumn()=='E')
					{

						$data[$row->getRowIndex()]['kType'] = $val; //是否补打考勤
						
						if($data[$row->getRowIndex()]['kType']=='1'){
							$data[$row->getRowIndex()]['repairTime']=$flagtime;
						}else
							$data[$row->getRowIndex()]['repairTime']="";
					}
					if($cell->getColumn()=='F')
					{
						if(!empty($val)&&($data[$row->getRowIndex()]['kType']=='1')){
							$data[$row->getRowIndex()]['ktime'] = strtotime(gmdate("Y-m-d H:i:s", \PHPExcel_Shared_Date::ExcelToPHP($val))); //补打时间
						}
					}
					if($cell->getColumn()=='G')
					{
						$data[$row->getRowIndex()]['reason'] = $val; //补打原因
					}					
				}
				
			}
		}
		foreach($data as $key => $val){
			$datenew[]= $val;
		}
		$result=$kaoqinAdd->addAll($datenew);
		if($result){
			$this->success("成功录入考勤",U("lists"));
		}else{
			$this->error("录入数据库时失败");
		}
    }
	/**
	 * //导出考勤excel
	 * $date = 考勤记录
	 * $re_kabout=考勤类型数组
	 */
	private function getExcel($date = array(),$rs_kabout=array()){
		if(empty($date)){
			$this->error("查询结果为空，不能导出数据");
		}
		//print_r($date);
		//exit;

		$objPHPExcel = new \PHPExcel();
		// set table header content
		$objPHPExcel->setActiveSheetIndex(0)
			->setCellValue('A1', '姓名')
			->setCellValue('B1', '身份证号')
			->setCellValue('C1', '打卡时间')
			->setCellValue('D1', '考勤类型')
			->setCellValue('E1', '是否补打(1:补打,0:正常)')
			->setCellValue('F1', '补打时间')
			->setCellValue('G1', '补打原因');

		foreach ($date as $k => $v) {
			$objPHPExcel->getActiveSheet(0)->setCellValue('A'.($k+2), $v['stName']);
			$objPHPExcel->getActiveSheet(0)->setCellValue('B'.($k+2), $v['stIDCard']);
			$objPHPExcel->getActiveSheet(0)->setCellValue('C'.($k+2), date("Y/m/d H:i:s",$v['ktime']));
			$objPHPExcel->getActiveSheet(0)->setCellValue('D'.($k+2), $rs_kabout[$v['kabout']]);
			$objPHPExcel->getActiveSheet(0)->setCellValue('E'.($k+2), $v['kType']);
			if(!empty($v['kType'])){
				$objPHPExcel->getActiveSheet(0)->setCellValue('F'.($k+2), date("Y/m/d H:i:s",$v['repairTime']));
				$objPHPExcel->getActiveSheet(0)->setCellValue('G'.($k+2), $v['reason']);
			}
		}

		// excel头参数
		header('Content-Type: application/vnd.ms-excel');
		header('Content-Disposition: attachment;filename="考勤表'.date('Y-m-d').'.xlsx"');  //日期为文件名后缀
		header('Cache-Control: max-age=0');

		ob_clean();//关键
		flush();//关键
		$objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');  //excel5为xls格式，excel2007为xlsx格式
		$objWriter->save('php://output');
		exit;
	}
	public function DelAll(){
		$this->LoginAreaAdmin();
		$this->LoginTrue();
		$kId=$_POST["node"];
		$kaoqin=M("kaoqin");

		foreach($kId as $val){
			$result=$kaoqin->where("kId={$val}")->delete();
		}
		$this->success("删除成功",U("lists"));
	}


	/**
	 * 查询每月的周数组
	 */
	public function getuserlist(){
		$id=$_POST["id"];
		$department=M("department");
		$staff=M("staff");
		$xiaozulist=$department->field('dId,dName')->where("pId='{$id}'")->select();
		$userlist=$staff->field('stId,stName,xiaozu')->where("regioneNum='{$id}'")->select();
		foreach($userlist as $key => $val){//按小组分类
			$userlistnew[$val['xiaozu']][]=$val;
		}
		foreach($xiaozulist as $key => $val){
			$xiaozulistnew[$val['dId']]=$val;
		}
		echo json_encode(array("userlist"=>$userlistnew,"xiaozulist"=>$xiaozulistnew));
		exit;
	}

	/**
	 * 查寻周内每天日期
	 */
	public function getweekofmonth(){
		$year = $_GET['year'];
		$month = $_GET['month'];
		//该月第一天
		$firstday = strtotime($year.'-'.$month.'-01');
		//该月的第一周有几天
		$firstweekday = (7 - date('N',$firstday) +1);
		//计算该月第一个周一的时间
		$starttime = $firstday-3600*24*(7-$firstweekday);
		//该月的最后一天
		$lastday = strtotime($year.'-'.$month.'-01'." +1 month -1 day");
		//该月的最后一周有几天
		$lastweekday = date('N',$lastday);
		//该月的最后一个周末的时间
		$endtime = $lastday-3600*24*$lastweekday;
		$step = 3600*24*7;//步长值
		$week_arr = array();
		for ($i=$starttime; $i<$endtime; $i= $i+3600*24*7){
			$week_arr[] = array('key'=>date('Y-m-d',$i).'|'.date('Y-m-d',$i+3600*24*6), 'val'=>date('Y-m-d',$i).'~'.date('Y-m-d',$i+3600*24*6));
		}
		echo json_encode($week_arr);
		die;
	}

}